package com.wsh.redis.redisdemo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author wsh
 * @date 2021/9/15 19:42
 */
@Slf4j
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    /**
     * 获取应用程序上下文
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }

    /**
     * 获取bean
     *
     * @param beanName bean名称
     * @return T
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        T bean = null;
        try {
            bean = (T) applicationContext.getBean(beanName);
        } catch (BeansException e) {
            log.error("获取bean异常：{}", e.getMessage());
            e.printStackTrace();
        }
        return bean;
    }

    /**
     * 获取bean
     *
     * @param clazz 类
     * @return T
     */
    public static <T> T getBean(Class<T> clazz) {
        T bean = null;
        try {
            bean = applicationContext.getBean(clazz);
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return bean;
    }
}
